<template>
  <div class="post-detail">
    <!-- 帖子内容展示 -->
    <h2>{{ tieziData.title }}</h2>
    <p>{{ tieziData.content }}</p>
    <p><strong>作者：</strong>{{ tieziData.user_name }} | <strong>发布时间：</strong>{{ tieziData.create_time }}</p>
    <p><strong>点赞数：</strong>{{ tieziData.like_num }}</p>

    <!-- 点赞按钮 -->
    <button @click="likePost(tieziData.id)">点赞</button>

    <!-- 回复按钮 -->
    <button @click="toggleReplies">{{ showReplies ? '收起' : '回复(' + tieziData.reply_num + ')' }}</button>

    <!-- 回复列表展示 -->
    <div v-if="showReplies" class="reply-container">
      <div v-if="login_status">
        <!-- 回复框 -->
        <el-form :model="replyForm" ref="form">
          <el-form-item label="">
            <el-input type="textarea" placeholder="请输入回复内容" v-model="replyForm.content"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="postReplys">发送回复</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div v-for="reply in replys" :key="reply.id" class="reply">
        <p><strong>{{ reply.user_name }}</strong> 评论：</p>
        <p>{{ reply.content }}</p>
        <p><strong>点赞数：</strong>{{ reply.like_num }}</p>
        <p><strong>回复时间：</strong>{{ reply.reply_time }}</p>
        <button @click="likeReply(reply.id, reply)">点赞</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { GetTieziReplys, PostLike, PostTeiziReply, GetTieziDetail } from '@/api/tiezi';
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';

const route = useRoute();
const postId = route.params.id;
const login_status = localStorage.getItem('login_status');
const storedUser = JSON.parse(localStorage.getItem('user_info'));

const tieziData = ref({});
const replys = ref([]);
const replyPage = ref(1);
const showReplies = ref(true);

const replyForm = ref({
  post_id: postId,
  content: '',
  user_id: storedUser?.id || null,
});

// 获取帖子详情
const getTieziDetail = async () => {
  try {
    const response = await GetTieziDetail(postId);
    tieziData.value = response.data.data;
  } catch (error) {
    console.error('Error:', error);
    ElMessage.error('获取帖子详情失败');
  }
};

// 发送回复
const postReplys = async () => {
  try {
    const response = await PostTeiziReply(replyForm.value);
    const { code, msg, errors, reply_id } = response.data;

    if (code === 200) {
      ElMessage.success(msg);
      replys.value.push({
        user_name: storedUser.username,
        content: replyForm.value.content,
        like_num: 0,
        reply_time: new Date().toLocaleString(),
        id: reply_id,
      });
      replyForm.value.content = '';
    } else if (code === 400) {
      if (errors) {
        for (const [field, errorMsg] of Object.entries(errors)) {
          ElMessage.error(`${field}: ${errorMsg}`);
        }
      } else {
        ElMessage.error(msg || '发送失败');
      }
    }
  } catch (error) {
    console.error('Error:', error);
    ElMessage.error('服务器错误，请稍后再试');
  }
};

// 点赞帖子
const likePost = async (post_id) => {
  tieziData.value.like_num++;
  const json = {
    user_id: storedUser.id,
    post_id: post_id,
  };
  try {
    const response = await PostLike(json);
    const { code, msg, errors } = response.data;

    if (code === 200) {
      ElMessage.success(msg);
    } else if (code === 400) {
      if (errors) {
        for (const [field, errorMsg] of Object.entries(errors)) {
          ElMessage.error(`${field}: ${errorMsg}`);
        }
      } else {
        ElMessage.error(msg || '点赞失败');
      }
    }
  } catch (error) {
    console.error('Error:', error);
    ElMessage.error('服务器错误，请稍后再试');
  }
};

// 点赞回复
const likeReply = async (replyId, reply) => {
  reply.like_num++;
  const json = {
    user_id: storedUser.id,
    reply_id: replyId,
  };
  try {
    const response = await PostLike(json);
    const { code, msg, errors } = response.data;

    if (code === 200) {
      ElMessage.success(msg);
    } else if (code === 400) {
      if (errors) {
        for (const [field, errorMsg] of Object.entries(errors)) {
          ElMessage.error(`${field}: ${errorMsg}`);
        }
      } else {
        ElMessage.error(msg || '点赞失败');
      }
    }
  } catch (error) {
    console.error('Error:', error);
    ElMessage.error('服务器错误，请稍后再试');
  }
};

// 切换回复列表的显示
const toggleReplies = async () => {
  showReplies.value = !showReplies.value;
  if (showReplies.value) {
    const res = await GetTieziReplys(postId, replyPage.value);
    replys.value = res.data.data;
  }
};

onMounted(async () => {
  await getTieziDetail();
  const res = await GetTieziReplys(postId, replyPage.value);
  replys.value = res.data.data;
});
</script>

<style scoped>
.post-detail {
  max-width: 900px;
  width: 100%;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.post-detail:hover {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}

h2 {
  font-size: 1.8rem;
  color: #333;
  font-weight: bold;
  margin-bottom: 15px;
}

p {
  color: #555;
  font-size: 1rem;
  line-height: 1.6;
  margin-bottom: 10px;
}

strong {
  color: #333;
}

button {
  background-color: #409EFF;
  color: white;
  border: none;
  padding: 8px 18px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  margin-right: 12px;
  margin-bottom: 10px;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #66b1ff;
}

button:disabled {
  background-color: #d3d3d3;
  cursor: not-allowed;
}

.reply-container {
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  position: relative;
}

.reply p {
  margin: 6px 0;
  font-size: 1rem;
  color: #333;
}

.reply button {
  background-color: #67C23A;
  padding: 6px 14px;
  font-size: 0.9rem;
  border-radius: 4px;
  margin-top: 8px;
}

.reply button:hover {
  background-color: #7ccf50;
}

.reply-time {
  color: #888;
  font-size: 0.9rem;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input__inner {
  height: 120px;
  font-size: 1rem;
  border-radius: 8px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  resize: none;
  box-sizing: border-box;
}

.el-button {
  font-size: 1rem;
  padding: 10px 20px;
  background-color: #409EFF;
  color: white;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.el-button:hover {
  background-color: #66b1ff;
}

@media (max-width: 768px) {
  .post-detail {
    margin: 10px;
    padding: 15px;
    max-width: 100%;
  }
  h2 {
    font-size: 1.5rem;
  }
  p {
    font-size: 0.9rem;
  }
  button {
    padding: 8px 12px;
    font-size: 0.9rem;
  }
  .reply button {
    padding: 6px 12px;
    font-size: 0.85rem;
  }
  .el-input__inner {
    height: 100px;
  }
}

@media (max-width: 480px) {
  .post-detail {
    margin: 5px;
    padding: 10px;
  }
  h2 {
    font-size: 1.3rem;
  }
  p {
    font-size: 0.85rem;
    line-height: 1.4;
  }
  button {
    width: 100%;
    margin: 5px 0;
  }
  .reply {
    padding: 10px 5px;
  }
}
</style>